﻿using System;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using WidgetInterface;

/// <summary>
/// Summary description for SQLDataSet
/// </summary>
/// 

namespace IndustrialDashboard
{
    public class SQLDataSet : IWidget
    {
        public struct FormatedTable
        {
            public List<object> columnsNamesList;
            public List<object> matrix;
        }

        public Dictionary<string, FormatedTable> tables;

        public SQLDataSet()
        {
            //
            // TODO: Add constructor logic here
            //
        }
        public SQLDataSet(DataSet ds)
        {
            try
            {
                tables = GetFormatedDataSet(ds);
            }
            catch (Exception ex) { }
        }

        private Dictionary<string, FormatedTable> GetFormatedDataSet(DataSet data)
        {
            return data.Tables.Cast<DataTable>().ToDictionary(t => t.TableName, t => GetFormatedTable(t));
        }
        private FormatedTable GetFormatedTable(DataTable table)
        {
            FormatedTable ft = new FormatedTable();
            try
            {
                ft.columnsNamesList = GetColumnNamesList(table);
                ft.matrix = GetMatrix(table);
                return ft;
            }
            catch (Exception ex) { throw ex; }
        }
        private List<object> GetColumnNamesList(DataTable table)
        {
            return table.Columns.Cast<DataColumn>().Select(c => (object)c.ColumnName).ToList();
        }
        private List<object> GetMatrix(DataTable table)
        {
            List<object> matrix = new List<object>();
            try
            {
                foreach (DataRow row in table.Rows)
                    matrix.AddRange(row.ItemArray.ToList());
                return matrix;
            }
            catch (Exception ex) { }
            return null;
        }

        #region IWidget Members

        public object GenerateResponse(DataSet ds)
        {
            SQLDataSet sqlds = new SQLDataSet(ds);
            return (Object)sqlds;
        }

        public object GetExcelChunk(System.IO.Stream document)
        {
            throw new NotImplementedException();
        }

        public object GetPDFChunk(System.IO.Stream document)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}
